package com.base.cn.platform.os.common.utils.TT;


import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.md5.MD5;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.http.HttpUtil;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.github.pagehelper.PageInfo;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static com.base.cn.platform.os.common.utils.BaseUtil.gson;


/**
 * @author LXR
 * @描述 3T直播执行方法
 * @Date 2020/6/08
 */
@Component
@Slf4j
public class TTServiceUtils {

    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 创建3T直播间
     *
     * @param className
     * @param notice
     * @param beginTime
     * @param endTime
     * @param type
     * @param teacherId
     * @param assistantId
     * @return
     */
    public Map<String, Object> create3TLiveData(String className, String notice, Date beginTime, Date endTime, String type, BigDecimal teacherId, BigDecimal assistantId) {
        if (StringUtils.isEmpty(className)) {
            return ResultUtil.ERROR("直播间名称不能为空");
        }
        if (className.trim().length() > 40) {
            return ResultUtil.ERROR("直播间名称不能大于40个字符");
        }
        if (StringUtils.isEmpty(notice)) {
            return ResultUtil.ERROR("直播间公告不能为空");
        }
        if (notice.trim().length() > 10000) {
            return ResultUtil.ERROR("直播间公告不能大于10000个字符");
        }
        if (ObjectUtils.isEmpty(beginTime)) {
            return ResultUtil.ERROR("请选择直播开始时间");
        }
        if (ObjectUtils.isEmpty(endTime)) {
            return ResultUtil.ERROR("请选择直播结束时间");
        }
        if (!beginTime.after(new Date())) {
            return ResultUtil.ERROR("直播开始时间要大于当前时间");
        }
        if (beginTime.after(endTime)) {
            return ResultUtil.ERROR("直播结束时间要大于开始时间");
        }
        if ((endTime.getTime() - beginTime.getTime()) > 60 * 3600000) {
            return ResultUtil.ERROR("只能创建60个小时之内的直播");
        }
        if (StringUtils.isEmpty(type)) {
            return ResultUtil.ERROR("请选择直播间类型");
        }
        Map parameter = new HashMap();
        parameter.put("className", className);
        parameter.put("notice", notice);
        parameter.put("type", type);
        parameter.put("beginTime", String.valueOf(beginTime.getTime() / 1000));
        parameter.put("endTime", String.valueOf(endTime.getTime() / 1000));
        parameter.put("isRecord", "1");
        parameter.put("uuid", teacherId.toString());
        parameter.put("assistantUuid", ObjectUtils.isNotEmpty(assistantId) ? assistantId.toString() : "");
        parameter.put("folderId", "");
        String url = "https://api3tclass.3ttech.cn/edu/create-room";
        Map<String, Object> resultMaps = request(url, parameter);
        if (resultMaps.containsKey("data")) {
            HashMap<String, String> mapTo = new HashMap<>();
            Map roomMap = (Map) resultMaps.get("data");
            mapTo.put("classId", (roomMap.get("classId").toString()));
            mapTo.put("teacherPcRoomUrl", roomMap.get("teacherPcRoomUrl").toString());
            mapTo.put("teacherRoomUrl", roomMap.get("teacherRoomUrl").toString());
            return ResultUtil.SUCCESS("直播间数据创建成功", mapTo);
        } else {
            Map map = (Map) resultMaps.get("error_info");
            return ResultUtil.ERROR("创建失败", map.get("error"));
        }
    }

    /**
     * 获取进入直播间参数
     *
     * @param params
     * @return
     * @throws IOException
     */
    public Map<String, Object> getLiveParam(Map params) {
        Map<String, Object> resultMaps = new HashMap<>();
        resultMaps = request("https://api3tclass.3ttech.cn/edu/enter-room", params);
        return ResultUtil.SUCCESS("成功", resultMaps.get("data"));
    }

    /**
     * 获取直播间人数
     *
     * @param classId
     * @return
     * @throws IOException
     */
    public Integer getLiveNumber(String classId) {
        Integer number = 0;
        Map params = new HashMap();
        params.put("classId", classId);
        Map<String, Object> resultMaps = request("https://api3tclass.3ttech.cn/edu/get-room-info", params);
        Map dataMap = (Map) resultMaps.get("data");
        number = Integer.valueOf(dataMap.get("onlineNum").toString());
        return number;
    }

    /**
     * 获取进入直播间详情
     *
     * @param classId
     * @return
     * @throws IOException
     */
    public Map<String, Object> getLiveInfo(String classId) {
        Map<String, Object> resultMaps = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("classId", classId);
        resultMaps = request("https://api3tclass.3ttech.cn/edu/get-room-info", params);
        return ResultUtil.SUCCESS("成功", resultMaps.get("data"));
    }

    /**
     * 获取直播间学员互动数据
     *
     * @param classId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Map<String, Object> getRoomInteractive(String classId, Integer pageNum, Integer pageSize) {
        Map<String, Object> resultMaps = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("classId", classId);
        params.put("uuid", "");
        params.put("page", pageNum.toString());
        params.put("pageSize", pageSize.toString());
        resultMaps = request("https://api3tclass.3ttech.cn/edu/get-room-interactive", params);
        return ResultUtil.SUCCESS("成功", resultMaps.get("data"));
    }

    /**
     * 获取直播间内聊天记录
     *
     * @param classId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Map<String, Object> getChatRecord(String classId, Integer pageNum, Integer pageSize) {
        Map<String, Object> resultMaps = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("classId", classId);
        params.put("uuid", "");
        params.put("page", pageNum.toString());
        params.put("pageSize", pageSize.toString());
        resultMaps = request("https://api3tclass.3ttech.cn/edu/get-chat-record", params);
        return ResultUtil.SUCCESS("成功", resultMaps.get("data"));
    }

    /**
     * 公共请求接口
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public Map<String, Object> request(String url, Map params) {
        //获取3T直播配置
        TreeMap<String, String> configMap = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
        params.put("SID", configMap.get("sid"));
        Long timestamp = System.currentTimeMillis() / 1000;
        params.put("safeKey", MD5.getMD5(configMap.get("safeKey") + timestamp));
        params.put("timeStamp", timestamp.toString());
        String result = "";
        try {
            result = HttpUtil.doPost(url, params);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.ERROR("");
        }
        Map<String, Object> map = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
        }.getType());
        return map;
    }

    /**
     * 获取回放视频码
     *
     * @param roomId
     * @return
     */
    public String getLivePlayBack(String roomId) {
        TreeMap<String, String> configMap = sysConfigService.getSysConfigContext(ConfigName.V96K);
        String customerKey = configMap.get("customerKey");
        Map param = new HashMap();
        param.put("classid", roomId);
        param.put("customerKey", customerKey);
        String livePlayBack = "";
        try {
            String result = HttpUtil.doPost("http://admin.96koo.net/common/videoApi/getVideoInfo", param);
            Map<String, Object> resultMap = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
            }.getType());
            if ("0".equals(resultMap.get("code")) && Integer.valueOf(resultMap.get("total").toString()).intValue() > 0) {
                List dataList = (List) resultMap.get("data");
                Map map = (Map) dataList.get(0);
                if ("finish".equals(map.get("status"))) {
                    livePlayBack = map.get("id_varchar").toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return livePlayBack;
    }

    public PageInfo<Map> findTTLivePage(Integer currentPage) {
        PageInfo<Map> pageInfo = new PageInfo<>();
        Map<String, String> params = new HashMap<>();
        params.put("pageSize", "20");
        params.put("page", currentPage.toString());
        Map<String, Object> resultMaps = request("https://api3tclass.3ttech.cn/edu/get-class-list", params);
        if (resultMaps.get("message").equals("success")) {
            Map map = (Map) resultMaps.get("data");
            pageInfo.setList((List<Map>) map.get("list"));
            String count = map.get("total").toString();
            setPageData((int) Double.parseDouble(count), 20, currentPage, pageInfo);
        }
        return pageInfo;
    }

    private void setPageData(int total, int pageSize, int currentPage, PageInfo<?> pageInfo) {
        pageInfo.setTotal(total);
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(currentPage);
        int pages = 0;
        if (total > pageSize) {
            if (total % pageSize == 0) {
                pages = total / pageSize;
            } else {
                pages = total / pageSize + 1;
            }
        } else {
            pages = 1;
        }
        pageInfo.setPages(pages);
        int[] navPageNums = null;
        if (pages > 0 && pages <= 8) {
            navPageNums = new int[pages];
            for (int i = 0; i < pages; i++) {
                navPageNums[i] = i + 1;
            }
        } else {
            navPageNums = new int[8];
            if (currentPage >= pages - 3) {
                for (int i = 0; i < 8; i++) {
                    navPageNums[i] = pages - 7 + i;
                }
            } else if (currentPage <= 5) {
                for (int i = 0; i < 8; i++) {
                    navPageNums[i] = i + 1;
                }
            } else {
                for (int i = 0; i < 8; i++) {
                    navPageNums[i] = currentPage - 4 + i;
                }
            }
        }
        pageInfo.setNavigatepageNums(navPageNums);
        if (pageInfo.getPageNum() == 1) {
            pageInfo.setIsFirstPage(true);
        }
        if (pageInfo.getPages() == pageInfo.getPageNum()) {
            pageInfo.setIsLastPage(true);
        }
    }


}